package lnu.project.cart;

import java.util.ArrayList;
import java.util.List;

import lnu.project.cart.entity.Basket;
import lnu.project.cart.entity.Product;
import lnu.project.cart.provider.BasketProvider;
import lnu.project.cart.provider.IBasketProvider;
import lnu.project.cart.provider.IProductProvider;
import lnu.project.cart.provider.ProductProvider;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends ListActivity {
	/** Providers **/
	private IBasketProvider basketProvider;
	private IProductProvider productProvider;

	/** Called when the activity is first created. */
	public static int POSITION = 0;
	private ListActivity this_activity;
	List<Basket> basket_list;
	private ListAdapter adapter;

	public static final int ADDBASKET = 0;
	public static final int EDITBASKET = 1;
	public static final int DELETEBASKET = 2;
	public static final int SENDSMS = 3;
	public static final int SENDEMAIL = 4;
	public static final int DELETEALL = 5;
	public static final int SHAREBASKET = 6;
	public static String BASKETNAME;
	public long IDtosearch;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this_activity = this;
		InitProviders();
		basket_list = basketProvider.GetAll();

		/* Adapter */
		adapter = new BasketAdapter(this, R.layout.main);
		setListAdapter(adapter);

		ListView lv = getListView();
		lv.setTextFilterEnabled(true); // Make list searchable
		lv.setOnItemClickListener(new ItemClick());

		/* Attach context menu on list */
		registerForContextMenu(getListView());
	}

	class BasketAdapter extends ArrayAdapter<Basket> {

		public BasketAdapter(Context context, int textViewResourceId) {
			super(context, textViewResourceId, basket_list);
		}

		@Override
		// Called when updating the ListView
		public View getView(int position, View convertView, ViewGroup parent) {
			View row;
			if (convertView == null) { // Create new row view object
				LayoutInflater inflater = getLayoutInflater();
				row = inflater.inflate(R.layout.main, parent, false);
			} else
				// reuse old row view to save time/battery
				row = convertView;

			/* Add new data to row object */
			TextView BaskeT = (TextView) row.findViewById(R.id.basket);
			String name = basket_list.get(position).getName();

			BaskeT.setText(name);
			return row;
		}
	}

	private void InitProviders() {
		this.basketProvider = new BasketProvider();
		this.basketProvider.SetActivity(this_activity);

		this.productProvider = new ProductProvider();
		this.productProvider.SetActivity(this_activity);
	}

	private void RefreshList() {
		basket_list.clear();
		List<Basket> tempBaskets = basketProvider.GetAll();
		for (Basket basket : tempBaskets) {
			basket_list.add(basket);
		}
		((BaseAdapter) adapter).notifyDataSetChanged();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent result) {
		Basket basket;
		if (resultCode == RESULT_OK) {
			int flag = Integer.parseInt(result.getStringExtra("flag"));
			System.out.println("Flag:" + flag);
			String name = result.getStringExtra("result");
			if (flag == 0) {
				System.out.println("New Basket");
				basket = new Basket(name);
				basketProvider.Create(basket);
			} else if (flag == 1) {
				basket = new Basket(IDtosearch, name);
				basketProvider.Update(basket);
			}
			RefreshList();
		}
	}

	/*
	 * Adding one option menu
	 */

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		MenuItem m1 = menu.add(0, ADDBASKET, 0, "New Basket"); // Create menu
																// 1
		m1.setIcon(android.R.drawable.ic_input_add); // Attach icon

		return result;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case ADDBASKET:
			Intent intent = new Intent(this_activity, AddNewBasket.class);
			this_activity.startActivityForResult(intent, 0);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/*
	 * Adding two context menus
	 */

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		menu.setHeaderTitle("Context Menu");
		menu.add(0, EDITBASKET, 0, "Edit Basket");
		menu.add(0, DELETEBASKET, 0, "Delete Basket");
		menu.add(0, SENDSMS, 0, "Send Basket/SMS");
		menu.add(0, SHAREBASKET, 0, "Share Basket");
		menu.add(0, SENDEMAIL, 0, "Send Basket/E-mail");
		menu.add(0, DELETEALL, 0, "Delete All Baskets");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		int pos = (int) info.position;
		long id = basket_list.get(pos).getId();
		switch (item.getItemId()) {
		case EDITBASKET:
			BASKETNAME = (String) basket_list.get(pos).getName();
			POSITION = pos;
			IDtosearch = id;
			Intent intent = new Intent(this_activity, EditBasket.class);
			this_activity.startActivityForResult(intent, 0);
			RefreshList();
			return true;

		case DELETEBASKET:
			System.out.println("Delete basket Id:" + id);
			basketProvider.Delete(id);
			RefreshList();
			return true;
		case SENDSMS:
			Intent intent2 = new Intent(this_activity, EnterPhonenum.class);

			Long value = id;

			System.out.println("ID: " + id);
			String svalue = value.toString();

			intent2.putExtra("basketId", svalue);
			intent2.putExtra("basketName", (String) basket_list.get(pos)
					.getName());
			this_activity.startActivityForResult(intent2, 0);
			return true;
		case SENDEMAIL:
			Intent intent3 = new Intent(this_activity, EnterEMAIL.class);
			this_activity.startActivityForResult(intent3, 0);
			return true;
		case DELETEALL:
			basketProvider.DeleteALL();
			RefreshList();
			return true;
		case SHAREBASKET:
			Basket basket = basketProvider.Get(id);
			basket = productProvider.LoadProduct(basket);
			String shareText = "My Basket's name is - " + basket.getName();
			for (Product p : basket.getProducts()) {
				shareText += "\n Name of item:" + p.getName();
				if (p.getBarcode() != null && p.getBarcode() != "") {
					shareText += " Barcode is:" + p.getBarcode();
				}
			}
			Intent share = new Intent(android.content.Intent.ACTION_SEND);
			share.setType("text/plain");
			share.putExtra(Intent.EXTRA_SUBJECT, "Please select the thing to share");
			share.putExtra(Intent.EXTRA_TEXT, shareText);
			startActivity(Intent.createChooser(share,
					"Please select the thing to share"));

			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	private class ItemClick implements OnItemClickListener {
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			Intent intent = new Intent(this_activity, BasketActivity.class);
			System.out.println("ID" + basket_list.get((int) position).getId());
			Long value = basket_list.get((int) position).getId();
			String svalue = value.toString();

			intent.putExtra("basketId", svalue);
			intent.putExtra("basketName", basket_list.get((int) position)
					.getName());

			this_activity.startActivity(intent);

		}
	}

}